<template>
  <div
      class="modal-overlay"
      :class="{ 'active': visible }"
      @click="handleOverlayClick"
  >
    <div class="modal-container" @click.stop>
      <button class="close-btn" @click="handleClose" aria-label="关闭">
        <Icon name="material-symbols:close" class="h-5 w-5" />
      </button>

      <div class="modal-header">
        <div class="tech-decoration"></div>
        <h2 class="modal-title">账户登录</h2>
        <p class="modal-subtitle">请输入您的账户信息以继续</p>
      </div>

      <form class="auth-form" @submit.prevent="handleSubmit">
        <div class="identity-switch">
          <button
              type="button"
              class="identity-btn"
              :class="{ active: loginWithUsername }"
              @click="loginWithUsername = true"
          >
            <Icon name="material-symbols:person" class="h-4 w-4 mr-2" />
            用户名
          </button>
          <button
              type="button"
              class="identity-btn"
              :class="{ active: !loginWithUsername }"
              @click="loginWithUsername = false"
          >
            <Icon name="material-symbols:alternate-email" class="h-4 w-4 mr-2" />
            邮箱
          </button>
        </div>

        <div class="form-group">
          <label
              :for="loginWithUsername ? 'username' : 'email'"
              class="form-label"
          >
            {{ loginWithUsername ? '用户名' : '邮箱' }}
          </label>
          <div class="input-wrapper">
            <Icon
                :name="loginWithUsername ? 'material-symbols:person' : 'material-symbols:alternate-email'"
                class="input-icon h-5 w-5"
            />
            <input
                :id="loginWithUsername ? 'username' : 'email'"
                type="text"
                v-model="identity"
                :placeholder="loginWithUsername ? '请输入用户名' : '请输入邮箱地址'"
                class="form-input"
                :class="{ error: identityError }"
                autocomplete="current-password"
            >
          </div>
          <p class="error-message" v-if="identityError">{{ identityError }}</p>
        </div>

        <div class="form-group">
          <label for="password" class="form-label">密码</label>
          <div class="input-wrapper">
            <Icon name="material-symbols:lock" class="input-icon h-5 w-5" />
            <input
                id="password"
                :type="showPassword ? 'text' : 'password'"
                v-model="password"
                placeholder="请输入密码"
                class="form-input"
                :class="{ error: passwordError }"
                autocomplete="current-password"
            >
            <button
                type="button"
                class="toggle-password"
                @click="showPassword = !showPassword"
                :title="showPassword ? '隐藏密码' : '显示密码'"
                aria-label="切换密码可见性"
            >
              <Icon :name="showPassword ? 'material-symbols:visibility' : 'material-symbols:visibility-off'" class="h-5 w-5" />
            </button>
          </div>
          <p class="error-message" v-if="passwordError">{{ passwordError }}</p>
        </div>

        <div class="forgot-password">
          <NuxtLink href="/forgetpassword" class="link" @click.prevent="handleForgotPassword">忘记密码?</NuxtLink>
        </div>

        <button
            type="submit"
            class="submit-btn"
            :disabled="isSubmitting"
        >
          <span v-if="!isSubmitting">
            <Icon name="material-symbols:login" class="h-4 w-4 mr-2" />
            登录
          </span>
          <span v-if="isSubmitting" class="loading">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
          </span>
        </button>
      </form>

      <div class="register-prompt">
        还没有账户?
        <NuxtLink href="/register" class="link primary" @click.prevent="handleRegisterRedirect">
          立即注册
        </NuxtLink>
      </div>

      <div class="google-login-section">
        <div class="divider">
          <span>或使用谷歌账号登录</span>
        </div>
        <button class="google-login-btn" title="使用谷歌账号登录" aria-label="谷歌登录" @click="handleGoogleLogin">
          <Icon name="fa-brands:google" class="google-icon h-5 w-5 mr-2"/>
          <span>
            使用谷歌登录
          </span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">

const props = defineProps<{
  visible: boolean;
}>();

// 发出的事件
const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'success', user: { id: string; name: string; email: string; avatar: string }): void;
  (e: 'register'): void;
  (e: 'forgot-password'): void;
  (e: 'google-login'): void;
}>();

// 状态管理
const loginWithUsername = ref<boolean>(true);
const showPassword = ref<boolean>(false);
const isSubmitting = ref<boolean>(false);

// 表单数据
const identity = ref<string>(''); // 用户名或邮箱
const password = ref<string>('');

// 错误信息
const identityError = ref<string>('');
const passwordError = ref<string>('');

// 关闭弹窗
const handleClose = () => {
  emit('close');
  // 重置表单
  setTimeout(() => {
    resetForm();
  }, 300);
};

// 点击遮罩层关闭
const handleOverlayClick = () => {
  handleClose();
};

// 处理注册跳转
const handleRegisterRedirect = () => {
  emit('register');
  handleClose();
};

// 处理忘记密码
const handleForgotPassword = () => {
  emit('forgot-password');
};

// 处理谷歌登录
const handleGoogleLogin = () => {
  emit('google-login');
};

// 重置表单
const resetForm = () => {
  identity.value = '';
  password.value = '';
  identityError.value = '';
  passwordError.value = '';
  isSubmitting.value = false;
};

// 表单验证
const validateForm = (): boolean => {
  let isValid = true;

  // 重置错误信息
  identityError.value = '';
  passwordError.value = '';

  // 验证身份（用户名或邮箱）
  if (!identity.value.trim()) {
    identityError.value = loginWithUsername.value
        ? '请输入用户名'
        : '请输入邮箱地址';
    isValid = false;
  } else if (!loginWithUsername.value && !isValidEmail(identity.value.trim())) {
    identityError.value = '请输入有效的邮箱地址';
    isValid = false;
  }

  // 验证密码
  if (!password.value) {
    passwordError.value = '请输入密码';
    isValid = false;
  } else if (password.value.length < 8) {
    passwordError.value = '密码至少8个字符';
    isValid = false;
  }

  return isValid;
};

// 邮箱格式验证
const isValidEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 处理表单提交
const handleSubmit = async () => {
  if (!validateForm()) {
    return;
  }

  isSubmitting.value = true;

  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1500));

    // 模拟登录成功
    const user = {
      id: Math.random().toString(36).substring(2, 10),
      name: loginWithUsername.value ? identity.value : identity.value.split('@')[0] || '',
      email: loginWithUsername.value ? `${identity.value}@example.com` : identity.value,
      avatar: '/image/usericon.jpg'
    };

    // 触发成功事件
    emit('success', user);

  } catch (error) {
    console.error('登录失败', error);
    identityError.value = '用户名/邮箱或密码错误';
  } finally {
    isSubmitting.value = false;
  }
};

// 监听visible变化，重置表单
watch(
    () => props.visible,
    (newVal) => {
      if (!newVal) {
        resetForm();
      }
    }
);
</script>

<style scoped>
/* 基础样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at center, rgba(22, 93, 255, 0.15) 0%, rgba(0, 15, 30, 0.85) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
  backdrop-filter: blur(8px);
}

.modal-overlay.active {
  opacity: 1;
  visibility: visible;
}

.modal-container {
  width: 100%;
  max-width: 420px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 15px 40px rgba(22, 93, 255, 0.2);
  overflow: hidden;
  transform: translateY(20px) scale(0.98);
  transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
  position: relative;
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.modal-overlay.active .modal-container {
  transform: translateY(0) scale(1);
}

/* 装饰元素 */
.tech-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #165DFF, #36CFC9);
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(22, 93, 255, 0.1);
  cursor: pointer;
  color: #64748b;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.close-btn:hover {
  background-color: #fff;
  color: #165DFF;
  transform: rotate(90deg);
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.15);
}

/* 标题区域 */
.modal-header {
  padding: 35px 30px 20px;
  text-align: center;
  position: relative;
}

.modal-title {
  margin: 0 0 10px 0;
  font-size: 1.6rem;
  color: #0A1629;
  font-weight: 600;
  letter-spacing: -0.5px;
}

.modal-subtitle {
  margin: 0;
  font-size: 0.95rem;
  color: #64748b;
  font-weight: 400;
}

/* 身份切换（用户名/邮箱） */
.identity-switch {
  display: flex;
  margin: 0 30px 20px;
  border: 1px solid rgba(22, 93, 255, 0.15);
  border-radius: 10px;
  overflow: hidden;
  background-color: rgba(22, 93, 255, 0.02);
}

.identity-btn {
  flex: 1;
  padding: 12px;
  background: none;
  border: none;
  font-size: 0.95rem;
  color: #64748b;
  cursor: pointer;
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.identity-btn.active {
  background: linear-gradient(135deg, #165DFF10, #165DFF05);
  color: #165DFF;
  font-weight: 500;
}

.identity-btn.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #165DFF;
}

/* 图标颜色 */
.identity-btn.active Icon[name="material-symbols:person"],
.identity-btn.active Icon[name="material-symbols:alternate-email"] {
  color: #165DFF;
}

/* 表单样式 */
.auth-form {
  padding: 0 30px 25px;
}

.form-group {
  margin-bottom: 22px;
}

.form-label {
  display: block;
  margin-bottom: 10px;
  font-size: 0.95rem;
  color: #334155;
  font-weight: 500;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  width: 100%;
  padding: 14px 15px 14px 45px;
  border: 1px solid rgba(22, 93, 255, 0.15);
  border-radius: 10px;
  font-size: 1rem;
  transition: all 0.25s ease;
  background-color: rgba(255, 255, 255, 0.7);
  color: #0A1629;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.03);
}

.form-input:focus {
  outline: none;
  border-color: #165DFF;
  box-shadow: 0 0 0 4px rgba(22, 93, 255, 0.1);
  background-color: #fff;
}

.form-input.error {
  border-color: #F53F3F;
}

.form-input.error:focus {
  box-shadow: 0 0 0 4px rgba(245, 63, 63, 0.1);
}

.input-icon {
  position: absolute;
  left: 14px;
  color: #86909C;
  transition: color 0.25s ease;
}

.form-input:focus + .toggle-password Icon,
.form-input:focus ~ .input-icon {
  color: #165DFF;
}

/* 密码切换按钮 */
.toggle-password {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  cursor: pointer;
  color: #86909C;
  width: 34px;
  height: 34px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
}

.toggle-password:hover {
  background-color: rgba(22, 93, 255, 0.05);
  color: #165DFF;
}

/* 错误信息 */
.error-message {
  margin: 6px 0 0 0;
  font-size: 0.85rem;
  color: #F53F3F;
  min-height: 1.2em;
  display: flex;
  align-items: center;
}

.error-message::before {
  content: "!";
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #F53F3F;
  color: white;
  font-size: 12px;
  text-align: center;
  line-height: 16px;
  margin-right: 6px;
  font-weight: bold;
}

/* 忘记密码 */
.forgot-password {
  text-align: right;
  margin: -12px 0 25px;
}

/* 链接样式 */
.link {
  color: #86909C;
  font-size: 0.9rem;
  text-decoration: none;
  transition: all 0.25s ease;
  position: relative;
  padding-bottom: 2px;
}

.link:hover {
  color: #165DFF;
}

.link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 1px;
  background-color: #165DFF;
  transition: width 0.25s ease;
}

.link:hover::after {
  width: 100%;
}

.link.primary {
  color: #165DFF;
  font-weight: 500;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(90deg, #165DFF, #0FC6C2);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(22, 93, 255, 0.2);
}

.submit-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: all 0.6s ease;
}

.submit-btn:hover:not(:disabled)::before {
  left: 100%;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(22, 93, 255, 0.3);
}

.submit-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.2);
}

.submit-btn:disabled {
  background: linear-gradient(90deg, #C9CDD4, #86909C);
  cursor: not-allowed;
  box-shadow: none;
}

.submit-btn Icon[name="material-symbols:login"] {
  color: white;
}

/* 加载动画 */
.loading {
  display: flex;
  gap: 8px;
}

.dot {
  width: 9px;
  height: 9px;
  background-color: white;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 注册提示 */
.register-prompt {
  text-align: center;
  padding: 0 30px 25px;
  font-size: 0.95rem;
  color: #64748b;
}

/* 谷歌登录区域 */
.google-login-section {
  padding: 0 30px 35px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 25px 0;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: linear-gradient(to right, transparent, rgba(22, 93, 255, 0.15), transparent);
}

.divider span {
  padding: 0 15px;
  font-size: 0.85rem;
  color: #86909C;
  position: relative;
}

.divider span::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background-color: rgba(22, 93, 255, 0.1);
  z-index: -1;
}

/* 谷歌登录按钮 - 修复图标颜色问题 */
.google-login-btn {
  width: 100%;
  padding: 14px;
  background-color: white;
  color: #333;
  border: 1px solid rgba(22, 93, 255, 0.15);
  border-radius: 10px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  gap: 10px; /* 图标和文字之间的间距 */
}

.google-login-btn:hover {
  background-color: #FAFAFA;
  border-color: rgba(22, 93, 255, 0.25);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.google-login-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

/* 谷歌图标品牌色 - 使用官方四色渐变 */
.google-login-btn Icon[name="fa-brands:google"] {
  background: conic-gradient(
      from -45deg,
      #ea4335 110deg,
      #4285f4 90deg 180deg,
      #34a853 180deg 270deg,
      #fbbc05 270deg
  ) 73% 55%/150% 150% no-repeat;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
  font-size: 1.25rem; /* 稍微增大图标 */
}


/* 响应式调整 */
@media (max-width: 480px) {
  .modal-container {
    margin: 0 15px;
    border-radius: 12px;
  }

  .modal-header,
  .auth-form,
  .google-login-section,
  .register-prompt {
    padding-left: 20px;
    padding-right: 20px;
  }

  .modal-title {
    font-size: 1.4rem;
  }
}
</style>
